<?php
require_once APPPATH . "controllers/cmsbase.php";
class cms_news extends CmsBase {

	var $_require_login = true;
	var $upload_config = null;

	function __construct() {
		parent :: __construct();
		// Check permission
		parent::_check_permission('pms_news');
		$this->load->model('Model_newsgroup', 'model_newsgroup');
		$this->load->model('Model_news', 'model_news');
		$this->load->helper('date');
	}

	/**
	 * Name: index
	 * Param: pagination param
	 * Description: Get list tbl_news_gr
	 *
	 */
	function index(){
		// Load pagination
		return $this->_render_my_view(array());
	}

	/**
	 *
	 *
	 */
	function browse_group(){
		$this->load->library('pagination');

		$start = 0;
		$limit = 10;
		$keyword = $this->input->get('keyword');

		$total = $this->model_newsgroup->browse_count($keyword);
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']):0;

		if($per_page){
			$start = $per_page;
		}

		$groups = $this->model_newsgroup->browse($keyword, $limit, $start);

		$config['base_url'] = "/?c=newsletter&m=browse_group";
		$config['uri_segment'] = 3;
		$config['total_rows'] = $total;
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		return $this->load->view("cms_news/browse_group", array("groups" => $groups));
	}

	/**
	 *
	 *
	 */
	function add_group()
	{
		$this->load->model('Model_newsgroup', 'model_newsgroup');
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$data = parse_input('item_', $_POST);
			// Update group
			$id = $this->model_newsgroup->insert_group($data);
			// redirect to browse
			$item = $this->model_newsgroup->find($id);
			$result = array('status' => 'success', 'message' => '');
			echo json_encode($result);
			exit;
		}
		else{
			// Get max sort
			$max_sort = $this->model_newsgroup->get_max_sort();
			$groups = $this->model_newsgroup->fetch_all();
			// Load edit group view
			return $this->load->view("cms_news/add_group", array("groups" => $groups));
		}
	}

	/**
	 *
	 *
	 */
	function edit_group($id = 0){
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$id = $this->input->post('id');
			if(intval($id)){
				$data = parse_input('item_', $_POST);
				// Update group
				$this->model_newsgroup->update_group($data, $id);
				// redirect to browse
				$result = array('status' => 'success',
								'message' => '',
								'id'=>$_POST['id'] ,
								'item_description'=>$_POST['item_description'],
								'item_name'=>$_POST['item_name'],
								'item_sort'=>$_POST['item_sort']);
				echo json_encode($result);
				exit;
			}
		}
		else{
			// Load newsletter group
			if(intval($id)){
				$group = $this->model_newsgroup->find($id);
				// Load edit group view
				return $this->load->view("cms_news/edit_group", array("group" => $group));
			}
		}
	}
	/**
	 *
	 *
	 */
	function delete_group($id){
		if(intval($id)){
			// get group id
			$this->model_newsgroup->delete_group($id);
			// redirect to browse
			$result = array('status' => 'success', 'message' => '');
			echo json_encode($result);
		}
		exit;
	}

	/**
	 *
	 *
	 */
	function browse_newsletter()
	{
		// Load pagination
		$this->load->library('pagination');
		$this->load->model('Model_news', 'model_news');
		$this->load->model('Model_newsgroup', 'model_newsgroup');

		$start = 0;
		$limit = 10;
		$search = null;
		$keyword = null;
		$fromdate = null;
		$todate = null;
		$group = null;
		$action = $this->input->post('actions');



		//print_r($_POST);exit;
		// if it dont post
		if($this->input->post('search')){
			$keyword = $this->input->post('keyword');
			$fromdate = $this->input->post('fromdate');
			$todate = $this->input->post('todate');
			$group = $this->input->post('group');
			$limit = $this->input->post('limit');
			if(!intval($limit)){
				$limit = 10;
			}

			// add to session
			$search = array('keyword' => $keyword,
							'fromdate' => $fromdate,
							'todate' => $todate,
							'group' => $group,
							'limit' => $limit);
			$_SESSION[NEWSLETTER_SEARCH] = $search;
		}
		elseif($action == 'delete'){

		}
		/*elseif($action == 'sendNewsletter'){
			// Save to session
			$newsletterIds = $this->input->post('newsletterIds');
			if(is_array($newsletterIds)){
				if(session_is_registered(NEWSLETTERIDS)){
					$newsletterIds = array_merge($newsletterIds, $_SESSION[NEWSLETTERIDS]);
				}
				$newsletterIds = array_unique($newsletterIds);
				$_SESSION[NEWSLETTERIDS] = $newsletterIds;
			}
			// Redirect to sendmail to member
			redirect('/?c=newsletter&m=send_newsletter', 'refresh');
		}*/
		elseif($action == 'update2Group'){
			$newsletterIds = $this->input->post('newsletterIds');
			$groupId = $this->input->post('groupId');
			if(is_array($newsletterIds)){
				// Add to group for emailIds
				foreach($newsletterIds as $item){
					$this->model_news->update_news(array('gid' => $groupId), $item);
				}
			}
		}
		else{
			if(session_is_registered(NEWSLETTER_SEARCH)){
				$search = $_SESSION[NEWSLETTER_SEARCH];
				$keyword = $search['keyword'];
				$fromdate = $search['fromdate'];
				$todate = $search['todate'];
				$group = $search['group'];
				$limit = $search['limit'];
			}
		}
		$_GET['per_page'] = $this->uri->segment(3,0);
		$total = $this->model_news->browse_count($keyword, $group, $fromdate, $todate);
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']):0;

		if($per_page){
			$start = $per_page;
		}

		$data = $this->model_news->browse($keyword, $group, $fromdate, $todate, $limit, $start);

		$config['base_url'] = site_url(array('c'=>'cms_news','m'=>'browse_newsletter'));
		$config['uri_segment'] = 3;
		$config['total_rows'] = $total;
		$config['per_page'] = $limit;
		$config['enable_query_strings'] = FALSE;
		$this->pagination->initialize($config);

		$groups = $this->model_newsgroup->fetch_all();
		return $this->load->view("cms_news/browse_newsletter", array("newsletters" => $data, 'search' => $search, 'groups' => $groups));
	}

	/**
	 *
	 *
	 */
	function add_newsletter()
	{
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$data = parse_input('newsletter_', $_POST);
			// update Newsletter
			$this->model_news->insert_news($data);
			// redirect to browse
			$result = array('status' => 'success', 'message' => '');
			echo json_encode($result);
			exit;
		}
		else{
			$groups = $this->model_newsgroup->fetch_all();
			return $this->load->view("cms_news/add_newsletter", array('groups' => $groups));
		}
	}

	/**
	 *
	 *
	 */
	function edit_newsletter($id = 0)
	{
		if(intval($id)){
			if($_SERVER['REQUEST_METHOD'] === 'POST')
			{
				// update Newsletter
				$data = parse_input('newsletter_', $_POST);
				// Update group
				$this->model_news->update_news($data, $id);

				$group = $this->model_newsgroup->find($_POST['newsletter_gid']);
				// redirect to browse
				$result = array('status' => 'success',
								'message' => '',
								'id' => $id,
								'item_name' => $_POST['newsletter_name'],
								'item_group' => @$group['name'],
								'item_postdate' => $_POST['newsletter_postdate'],
								'item_sort' => $_POST['newsletter_sort'],
								'item_img' => $_POST['newsletter_img'],

						  );
				echo json_encode($result);
				exit;
			}
			else{
				$groups = $this->model_newsgroup->fetch_all();
				$newsletter = $this->model_news->find($id);
				return $this->load->view("cms_news/edit_newsletter", array("newsletter" => $newsletter, 'groups' => $groups));
			}
		}
	}

	/**
	 *
	 *
	 */
	function delete_newsletter($id)
	{
		$this->load->model('Model_news', 'model_news');
		// redirect to browse
		if(intval($id)){
			// get group id
			$this->model_news->delete_news($id);
			// redirect to browse
			$result = array('status' => 'success', 'message' => '');
			echo json_encode($result);
		}
		exit;
	}

	/**
	 *
	 *
	 */
	function send_newsletter(){
		$emails = null;
		$newsletters = null;
		if($this->input->post('send'))
		{
			// After sent delete session
			if(session_is_registered(EMAILID_NEWSLETTER)){
				// Send Newsletter to member

				$subject = $this->input->post("subject");
				$content = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head></head><body>';
				$content .= $this->input->post("content");
				$content .= "</body></html>";
				// Parse content to add unsubscribe
				$salt = $this->config->item('salt');

				$mailIds = $_SESSION[EMAILID_NEWSLETTER];
				$this->load->model('Model_vnmail', 'model_vnmail');
				$emails = $this->model_vnmail->find_by_ids($mailIds);
				if(is_array($emails)){
					foreach($emails as $key => $val){
						$data = str_replace("m=unsubscribe", "m=unsubscribe&l1=287&salt=".md5($val['email'].$salt), $content);
						newsletter_sendmail($val['email'], $subject, $data);
						//echo $val['email'];
					}
				}
				//newsletter_sendmail("trinm@purpleasia.com,minhtri2711@gmail.com", $subject, $content);
				//newsletter_sendmail("hien@purpleasia.com", $subject, $content);
				//newsletter_sendmail("chauvn@purpleasia.com", $subject, $content);
				// Clear session
				session_unregister(EMAILID_NEWSLETTER);
				session_unregister(NEWSLETTERIDS);
			}
			return $this->render("newsletter/notice", array('emails' => $emails, 'messages' => 'You have just sent successful email! '));
		}
		elseif($this->input->post('generate')){
			$mails = null;
			$newsletters = null;
			if(session_is_registered(EMAILID_NEWSLETTER)){
				$mailIds = $_SESSION[EMAILID_NEWSLETTER];
				if(!empty($mailIds)){
					$selectedEmailIds = $mailIds;

					$this->load->model('Model_vnmail', 'model_vnmail');
					$emails = $this->model_vnmail->find_by_ids($selectedEmailIds);
					$this->load->model('Model_vnmailgroup', 'model_vnmailgroup');
					if(is_array($emails)){
						foreach($emails as $key => $val){
							$emails[$key]['groups'] = $this->model_vnmailgroup->fetch_groupbymailid($val['id']);
						}
					}
				}
			}
			if(session_is_registered(NEWSLETTERIDS)){
				$newsletterIds = $_SESSION[NEWSLETTERIDS];

				$this->load->model('Model_news', 'model_news');
				$newsletters = $this->model_news->find_by_ids($newsletterIds);
				//echo $this->db->last_query();
			}
			return $this->render("newsletter/generate_email", array('emails' => $emails, 'newsletters' => $newsletters));
		}
		else{
			if($this->input->post('delete')){
				// Delete email id save in session
				if(session_is_registered(EMAILID_NEWSLETTER)){
					$mailIds = $_SESSION[EMAILID_NEWSLETTER];
					$selectedEmailIds = $this->input->post('mailIds');
					if(is_array($selectedEmailIds)){
						foreach($selectedEmailIds as $item){
							$key = array_search($item, $mailIds);
							if($key===null){

							}
							else{
								unset($mailIds[$key]);
							}
						}
						$_SESSION[EMAILID_NEWSLETTER] = $mailIds;
					}
				}
				// Delete newsletter id that saved in session
				if(session_is_registered(NEWSLETTERIDS)){
					$newsletterIds = $_SESSION[NEWSLETTERIDS];
					$selectedNewsletterIds = $this->input->post('newsletterIds');
					//var_dump($selectedNewsletterIds);
					if(is_array($selectedNewsletterIds)){
						foreach($selectedNewsletterIds as $item){
							$key = array_search($item, $newsletterIds);
							if($key===null){

							}
							else{
								unset($newsletterIds[$key]);
							}
						}
						$_SESSION[NEWSLETTERIDS] = $newsletterIds;
					}
				}
			}
			$mails = null;
			$newsletters = null;
			// Don't support pagination
			// $this->load->library('pagination');
			if(session_is_registered(EMAILID_NEWSLETTER)){
				$mailIds = $_SESSION[EMAILID_NEWSLETTER];
				if(!empty($mailIds)){
					$selectedEmailIds = $mailIds;

					$this->load->model('Model_vnmail', 'model_vnmail');
					$emails = $this->model_vnmail->find_by_ids($selectedEmailIds);
					$this->load->model('Model_vnmailgroup', 'model_vnmailgroup');
					if(is_array($emails)){
						foreach($emails as $key => $val){
							$emails[$key]['groups'] = $this->model_vnmailgroup->fetch_groupbymailid($val['id']);
						}
					}
				}
			}
			if(session_is_registered(NEWSLETTERIDS)){
				$newsletterIds = $_SESSION[NEWSLETTERIDS];
				if(is_array($newsletterIds) AND count($newsletterIds) > 0){
					$this->load->model('Model_news', 'model_news');
					$newsletters = $this->model_news->find_by_ids($newsletterIds);
				}
			}
		}
		return $this->render("newsletter/send_newsletter", array('emails' => $emails, 'newsletters' => $newsletters));
	}

	function get_newest_newsgroup(){
		$this->load->model('Model_newsgroup', 'model_newsgroup');
		$result = $this->model_newsgroup->find($this->model_newsgroup->get_newest());
		$group = $result['id'];
		$count = $this->model_newsgroup->count_all();
		$class = ($count%2) ? 'odd' : 'even';
		$str = "<tr class='$class' id='".$result['id']."'>";
		$str .= "<td class='small'><a class='ajax-edit' href='".site_url(array("c" => "cms_news", "m" => "edit_group", "id" => $group))."' alt='Edit''><img src='".image_url()."icons/edit.gif' alt='Edit'/></a></td>";
		$str .= "<td class='small'><a class='ajax-delete' href='".site_url(array("c" => "cms_news", "m" => "delete_group", "id" => $group))."' alt='Delete''><img src='".image_url()."icons/del.gif' alt='Delete'/></a></td>";
		$str .= "<td class='item_name'>".$result['name']."</td>";
		$str .= "<td class='item_description'>".$result['description']."</td>";
		$str .= "<td class='small'>".$result['quantity']."</td>";
		$str .= "<td class='small item_sort'>".$result['sort']."</td>";
		$str .= "</tr>";
		echo $str;
	}

	function get_newest_news(){
		$this->load->model('Model_news', 'model_news');
		$this->load->model('Model_newsgroup', 'model_newsgroup');
		$result = $this->model_news->find($this->model_news->get_newest());

		$group = $this->model_newsgroup->find($result['gid']);


		$count = $this->model_news->count_all();
		$class = ($count%2) ? 'odd' : 'even';
		$str = "<tr class='$class' id='".$result['id']."'>";
		$str .= "<td class='small'><input type='checkbox' class='newsletterId' name='newsletterIds[]' value='".$result['id']."'/></div>";
		$str .= "<td class='small'><a class='ajax-edit' href='".site_url(array("c" => "cms_news", "m" => "edit_newsletter", "id" => $result['id']))."' alt='Edit''><img src='".image_url()."icons/edit.gif' alt='Edit'/></a></td>";
		$str .= "<td class='small'><a class='ajax-delete' href='".site_url(array("c" => "cms_news", "m" => "delete_newsletter", "id" => $result['id']))."' alt='Delete''><img src='".image_url()."icons/del.gif' alt='Delete'/></a></td>";
		$str .= "<td class='item_g_name'>".$group['name']."</td>";
		$str .= "<td class='item_image'><img src='".userfile_img_url($result['img'])."' style='max-width: 220px;'/></td>";
		$str .= "<td class='item_name'><a class='dyna' href='#' title='".htmlspecialchars($result['description'])."'>".$result['name']."</td>";
		$str .= "<td class='small'>".$result['postdate']."</td>";
		$str .= "<td class='small item_sort'>".$result['sort']."</td>";
		$str .= "</tr>";
		echo $str;
	}

}
?>
